package org.iabako.server.filter;

import org.iabako.shared.iservice.security.AuthenticateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * This filter guarantee spring security for GWT asynchronous services
 * (they aren't filtered by standard spring security rules and filters)
 *
 * Created by jose on 29/09/14.
 */

public class SpringSecurity4GwtFilter extends DelegatingFilterProxy {

    @Autowired
    AuthenticateService authenticateService;


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String requestPath = ((SecurityContextHolderAwareRequestWrapper) request).getServletPath();
        String requestURI = ((SecurityContextHolderAwareRequestWrapper) request).getRequestURI();

        if (authenticateService.getAuthenticatedUser() == null
                && requestPath.contains("/iabakoServices")
                && !requestURI.contains("/iabakoServices/extranet/")) {
            //user must be authenticated
            ((HttpServletResponse) response).sendRedirect("/pages/nosession");
            return;

        } else if ("/".equals(requestURI)) {

            request.getRequestDispatcher("/iabako/").forward(request, response);
            return;
        }

        filterChain.doFilter(request, response);
    }
}
